<template>
    <div class="up-file" v-if="type==='button'">
        <span>{{buttontext||'导入'}}</span>
        <input type="file" id="file_input" :accept="accept" @change="upfile" />
    </div>
    <div class="up" v-else>
        <img v-if="obj.fileUrl && isImg" :src="imgUrl" class="avatar" />
        <span v-else-if="obj.fileUrl && !isImg" :data-fileurl="obj.fileUrl" class="avatar-uploader-file"></span>
        <span v-else class="avatar-uploader"></span>
        <input type="file" :accept="accept" @change="upfile" />
        <span class="up_del" v-show="obj.fileUrl" @click="del"></span>
        <div class="progress" v-show="obj.progressFlag">
            <span><u :style="'width:'+obj.loadProgress"></u></span>
            <i>{{obj.loadProgress}}</i>
        </div>
    </div>
    <div v-if="type==='button'&&obj.fileUrl" class="w100 hidden">
        <div @click="PreviewFile(imgUrl)" class="w100 pointer lineOne">{{ obj.fileUrl.substring(0,8) }}.{{ obj.fileUrl.split('.')[1] }}</div>
    </div>

    <div class="pre-dialog" v-if="obj.PreviewObj.Visible" @click="obj.PreviewObj.Visible=false">
        <div class="close-icon" @click="obj.PreviewObj.Visible=false">
            <el-icon style="margin-top: 7px;" color="#fff">
                <Close />
            </el-icon>
        </div>
        <el-image v-if="['jpg','png','jpeg','gif'].includes(obj.PreviewObj.type)" class="h100" :src="obj.PreviewObj.fileURL" fit="cover" @click.stop="()=>{}" />
        <iframe v-else-if="['pdf'].includes(obj.PreviewObj.type)" :class="[proxy.$utils.isMobile()?'w100':'w80']" class="h100" :src="obj.PreviewObj.fileURL"></iframe>
        <div v-else :class="[proxy.$utils.isMobile()?'w100':'w80']" class="h100 w-bg flex-center mini-gray-size">
            <a class="nodata-a" download :href="obj.PreviewObj.fileURL">-- 不支持预览 点击下载 --</a>
        </div>
    </div>
</template>

<script setup>
    import { reactive, getCurrentInstance, computed, watch } from 'vue'
    import { Close } from "@element-plus/icons-vue";
    let { proxy } = getCurrentInstance()
    const emit = defineEmits(['update:file',"update:filesize","update:originname"]) //此处要完全对应，采用固定的update:prop属性

    const props = defineProps({
        accept: { type: Array, default: ['image/jpeg','image/png','image/gif','image/webp'] },
        debug: { type: Boolean, default: false },
        file: { type: String, default: "", require: true },
        filesize: { type: Number, default: 0 },
        originname: { type: String, default: "" },
        dir: { type: String, default: "" }, //计算属性中用来回显的
        rename: { type: Boolean, default: true }, //默认要改名
        maxsize: { type: Number, default: 1024 * 1024 * 5 }, //单位K，默认5120K，即5M
        maxwidth: { type: Number, default: 0 },
        maxheight: { type: Number, default: 0 },
        background: { type: String, default: "" },
        type: { type: String, default: "" },
        buttontext: { type: String, default: "导入" },
    })

    let isUpload = false //默认没上传过
    let obj = reactive({
        fileUrl: '',
        progressFlag: false,
        loadProgress: "0%",
        PreviewObj: {
            Visible: false,
            type: '',
            fileURL: ''
        },
    })

    let imgUrl = computed(() => {
        if(!isUpload && obj.fileUrl != ""){ //没上传过，且传入值不为空，表示这是默认值
            return proxy.$setting.globalUrl.fileurl + '/' + props.dir + '/' + obj.fileUrl
        }
        if (isUpload && obj.fileUrl != ""){ //上传过，且有值
            return proxy.$setting.globalUrl.upload + '/' + obj.fileUrl
        }
        return ""
    })

    let isImg = computed(() => {
        if(obj.fileUrl == "") return false;
        return ['jpg','jpeg','png','gif','webp'].some(t => t == obj.fileUrl.split('.').pop().toLowerCase())
    })

    watch(
        () => props.file,
        (val) => {
            obj.fileUrl = props.file
        }
    )

    let del = () => {
        obj.fileUrl = "";
        emit('update:file', "");
        emit('update:filesize', 0);
        emit('update:originname', "");
    }

    let upfile = e =>{
        let file = e.srcElement.files[0]
        e.target.value=''
        if (!file) return //用户点了取消，会触发这个，加上这个判断，就不会继续了
        if (props.debug) console.log(file.type)
        let isType = props.accept.some(t => t === file.type)
        if (file.type == "") isType = true //如果就没拿到file.type（这是有可能的），就认为是过
        if (props.accept.length <= 0) isType = true //如果没格式要求，也认为是过
        const isLimit = file.size < props.maxsize

        if (!isType) {
            proxy.elMessageMixin(`只能上传${props.accept.join(',')}格式`, 'error')
            return
        }
        if (!isLimit) {
            proxy.elMessageMixin(`不能超过${props.maxsize/(1024*1024)}M`, 'error')
            return
        }

        //检查完成，可以上传
        let formData = new FormData(); //这样可以给form参数了
        formData.append("type", file.type);
        emit('update:originname', file.name);
        emit('update:filesize', file.size);
        formData.append("file", file);
        formData.append("rename", props.rename ? 0 : 1);
        if (props.maxwidth > 0) formData.append("maxheight", props.maxwidth);
        if (props.maxheight > 0) formData.append("maxwidth", props.maxheight);
        if (props.background != "") formData.append("background", props.background);

        proxy.$ajax({
            baseURL: "",
            url: proxy.$setting.globalUrl.uploadserver,
            data: formData,
            isUploadFile: true,
            bfLoading: false,
            timeout: 0,
            progress: p => {
                obj.progressFlag = true
                obj.loadProgress = (p.loaded / p.total * 100 | 0) + '%'
            }
        }).then(res => {
            isUpload = true
            obj.fileUrl = res.filename
            emit('update:file', res.filename)
            emit('upload',res.filename)
            obj.progressFlag = false
        }).catch((() => obj.progressFlag = false))
    }

    const PreviewFile=(fileUrl)=>{
        if(!fileUrl){
            return
        }
        console.log('fileUrl',fileUrl);
        obj.PreviewObj = {
            Visible: true,
            type: fileUrl.split(/\.(?=[^\.]+$)/)[1],
            fileURL: fileUrl
        }
    }
</script>

<style scoped lang="scss">
    $w: 120px;
    $h: 120px;
    $color: #d8dae2;
    .up { position: relative; width: $w; height: $h+20; overflow: hidden;
        .up_del { position: absolute; top: 0; right: 6px; 
            &::after { content: "\e74b"; font-family: "iconfont"; font-size: 10px; }
        }
        input { position: absolute; top:-20px; font-size:0; appearance:none; width: $w; height: $h+20; }
        .avatar { position: absolute; width: $w; height: $h; object-fit: contain; box-sizing: border-box; border: 1px solid $color; }
        .avatar-uploader, .avatar-uploader-file { width: $w; height: $h; background-color: #FFF; border: 1px solid $color; box-sizing: border-box; display: flex; justify-content: center; align-items: center; 
            &::after { content:'\e6b7'; font-family: "iconfont"; font-size: 40px; }
        }
        .avatar-uploader::after { color: $color; content:'\e626'; }
        .progress { position:absolute; bottom:0; display: flex; width:120px; margin-top: 3px; align-items: center; 
            * { display: flex; font-style: normal; font-size: 12px; }
            span { flex: 1; align-items: center; height:6px; border-radius: 3px; background-color: $color; margin-right: 5px; }
            u { background-color: #3a4fbd; height:6px; border-radius: 3px; }
        }
    }
    .up-file{
        position: relative;height: 32px; padding: 0 10px; overflow: hidden;line-height: 32px;text-align: center;font-size: 12px; border-radius: 5px; background-color: $end-color !important; color: #fff;
        display: inline-block; cursor: pointer;
        input{
            position: absolute;height: 32px; width: 100%; top:0px; left:0; font-size:0; -webkit-appearance:none;opacity: 0;cursor: pointer;
        }
    }


    .pre-dialog{
        position: fixed; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5);
        display: flex; justify-content: center; align-items: center; z-index: 9999;
        .close-icon{
            position: absolute; right: 0; top: 0; z-index: 999989999999434; font-size: 28px; background: #606266; cursor: pointer;
            width: 44px; height: 44px; border-radius: 44px; line-height: 44px; text-align: center;
        }
    }
    iframe{
        border: none !important;
    }
    .nodata-a{color: #999;}
    .nodata-a:hover{color: #409eff;}
</style>